<template>
  <div class="emission-item" :style="[{left:`${left}px`},{top:`${top}px`}]"
       v-drag:position="{set:set, top: top, left: left, setSend:setSend}">
    <div class="item-border">{{ name }}</div>
  </div>
</template>

<script>
export default {
  props: {
    top: {
      type: Number,
      default: 0
    },
    left: {
      type: Number,
      default: 0
    },
    item: {
      type: Object,
      default: function () {
        return {
          name: "铁矿石"
        }
      }
    },
    name: {
      type: String,
      default: function () {
        return "铁矿石"
      }
    }
  },
  mounted() {

  },
  methods: {
    set(left, top) {
      this.position.top = top
      this.position.left = left
    },
    setSend() {
      this.$emit("move", this.position, this.name)
    }
  },
  beforeDestroy() {

  },
  data() {
    return {
      position: {
        top: 0,
        left: 0,
      },
    }
  },
  // 自定义指令 实现可拖动
  directives: {
    drag(el, bindings) {
      el.onmousedown = function (e) {
        var disx = e.pageX - el.offsetLeft
        var disy = e.pageY - el.offsetTop
        document.onmousemove = function (e) {
          el.style.left = e.pageX - disx + 'px'
          el.style.top = e.pageY - disy + 'px'
          bindings.value.set(e.pageX - disx, e.pageY - disy)
        }
        document.onmouseup = function () {
          // 松手后恢复位置
          bindings.value.setSend()
          el.style.left = bindings.value.left + "px"
          el.style.top = bindings.value.top + "px"
          document.onmousemove = document.onmouseup = null
        }
      }
    }
  }
}
</script>

<style>
.emission-item {
  position: absolute;
}

.item-border {
  width: 80px;
  height: 40px;
  line-height: 40px;
  font-size: 18px;
  text-align: center;
  margin: 0 auto;
  border-radius: 10px;
  background-color: #6a9774;
  color: #fff;
}
</style>
